<?PHP
// vim: set expandtab tabstop=4 shiftwidth=4:
// +----------------------------------------------------------------------+
// | SAPID: XML Sapiens Engine Demonstrator                               |
// +----------------------------------------------------------------------+
// | Author:  Max Baryshnikov aka Mephius <mb@rg.by>	                  |
// | Copyright (c) 2004 Max Baryshnikov                                   |
// | http://sapid.sourceforge.net	                                      |
// +----------------------------------------------------------------------+
// | This source file is free software; you can redistribute it and/or    |
// | modify it under the terms of the GNU Lesser General Public           |
// | License as published by the Free Software Foundation; either         |
// | version 2.1 of the License, or (at your option) any later version.   |
// |                                                                      |
// | This source file is distributed in the hope that it will be useful,  |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
// | Lesser General Public License for more details.                      |
// +----------------------------------------------------------------------+
// Release: 13.11.04 (dd/mm/yy)
// $Id: insert_image.php,v 1.5 2005/08/15 13:28:33 sheiko Exp $

session_start();
header("Content-type: text/html; charset=UTF-8");
if(!isset($_SESSION["user"]["LOGIN"]) or (isset($_SESSION["user"]["NOLOGIN"]) and $_SESSION["user"]["NOLOGIN"]!="")) die();


include_once("../../etc/rc.conf.php");
if($language=="ru" or $language=="en") $default_language=$language;
if(!$default_language) $default_language="en";


// ROOT_PATH = preg_replace("/usr\/system\/insert_image\.php$/is", "", $_SERVER["SCRIPT_FILENAME"]);
include_once('../../lang/'.$default_language.'.inc.php');


function message_die($message) {
	die('
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<title>Critical error</title>
	<link rel="stylesheet" type="text/css" href="'.$GLOBALS["http_path"].'usr/system/default.css" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body style="padding: 0px; margin: 0px;">
<div style="position: absolute; left: 15%; top: 10%">
	<div style="position: absolute; z-index: 2;"><img src="'.$GLOBALS["http_path"].'usr/system/images/girl.gif" width="100" height="193" alt="Beastie girlfriend"></div>
	<div style="padding: 125px 0px 0px 25px;">
	<table class="tpanel" style="width: 90%" cellspacing=0 cellpadding=0>
		<tr>
			<td class="header" style="text-align: center;"><b>Critical error</b></td>
		</tr>
		<tr>
			<td style="padding: 20px; font-family: Verdana, Arial;">
			'.$message.'
			</td>
		</tr>
		<tr>
			<td class="header" align="right">&nbsp;</td>
		</tr>
	</table>
	</div>
</div>
</body>
</html>');
}



/**
 * @desc Save POST data
 */

if($_POST)
{

	include('image_resize.inc.php');

	$dcontentpath = ROOT_PATH."usr/templates/images/";
	$filebasename=$_FILES["ImgUrl"]['name'];
	$prefix = (int)$_POST["id"];

	if( preg_match("/\.php$/is", $filebasename) ) $filebasename = $filebasename.".txt";
	if( preg_match("/\.phtml$/is", $filebasename) ) $filebasename = $filebasename.".txt";
	if( preg_match("/\.php3$/is", $filebasename) ) $filebasename = $filebasename.".txt";


	if($_FILES["ImgUrl"]['tmp_name']!="" AND $_FILES["ImgUrl"]['tmp_name']!="none") {

		@unlink($dcontentpath.$prefix.".".$filebasename);
		@copy($_FILES["ImgUrl"]['tmp_name'], $dcontentpath.$prefix.".".$filebasename);
		if(!file_exists( $dcontentpath.$prefix.".".$filebasename )) message_die($lang["Can_not_save_uploaded_file"]);
		else {
			$tmp_name = $dcontentpath.$prefix.".".$filebasename;
			@chmod (dcontentpath_pref.$prefix.".".$filebasename, 0755);
			if($_POST["resize_width"] AND $_POST["resize_height"]) {
				$farr = array (
				'tmp_name' => $tmp_name,
				'name' => $_FILES["ImgUrl"]['name'],
				'type' => $_FILES["ImgUrl"]['type'],
				'error' => $_FILES["ImgUrl"]['error'],
				'size' => $_FILES["ImgUrl"]['size']);

				create_tnail($farr, $_POST["resize_width"], $_POST["resize_height"],  $dcontentpath , $prefix."."  );
			}
			if($_POST["icon_width"] AND $_POST["icon_height"]) {
				$farr = array (
				'tmp_name' => $tmp_name,
				'name' => $_FILES["ImgUrl"]['name'],
				'type' => $_FILES["ImgUrl"]['type'],
				'error' => $_FILES["ImgUrl"]['error'],
				'size' => $_FILES["ImgUrl"]['size']);

				create_tnail($farr, $_POST["icon_width"], $_POST["icon_height"],  $dcontentpath , "icon_".$prefix."."  );
			}
		}
	}

	$content = '<body>
'.( $error_message ? "<br /><br /><br /><br /><div align=\"center\">'".$error_message."'</div>\n" :
'<script language="JavaScript">
 	window.opener.document.getElementById(\'flag_unload_access\').value = 1;
	//window.opener.window.close();
	window.close();
</script>
').'
</body>
';
print $content;
exit;
}


if( !file_exists(ROOT_PATH.'usr/templates/images/imgpreview.gif') ) message_die('I can\'t find file /usr/templates/images/imgpreview.gif');
if( !file_exists(ROOT_PATH.'usr/templates/images/dot.swf') ) message_die('I can\'t find file /usr/templates/images/dot.swf');

?>
<html>
<head>
	<title><?=$lang["Insert_Picture"]?></title>
	<style type="text/css">
	 BODY   {margin-left:10; font-family:Verdana; font-size:10pt; background:menu}
	 BUTTON {width:9em}
	 TABLE  {font-family:Verdana; font-size:10pt;}
	 P      {text-align:center}
	</style>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link rel="stylesheet" type="text/css" href="<?PHP print $http_path; ?>usr/system/default.css">


<script language="JavaScript">
<!--
var imgCaptions = new Array();
var imgHeights = new Array();
var imgWidths = new Array();
var triggerPreview = false;
imgCaptions[0] = "";
imgHeights[0] = "0";
imgWidths[0] = "0";


function IsDigit() {
	return ((event.keyCode >= 48) && (event.keyCode <= 57));
}


function showPreview() {


	if(document.frmImagePick.ImgUrl.value != "")
	document.frmImagePick.BackupImgUrl.value = document.frmImagePick.ImgUrl.value;

	if (document.frmImagePick.BackupImgUrl.value != "")
	{
		triggerPreview = true;
		var arg_arr = document.frmImagePick.BackupImgUrl.value.split(".");
		var arg_ext =  arg_arr[arg_arr.length-1];
		if(arg_ext=="swf" || arg_ext=="SWF") {
			document.getElementById('DIVIMG').style.display = "none";
			document.getElementById('DIVSWF').style.display = "block";
			document.getElementById('PREVIEWPIC').Movie=decodeURI(document.frmImagePick.BackupImgUrl.value);
		} else {
			document.getElementById('DIVSWF').style.display = "none";
			document.getElementById('DIVIMG').style.display = "block";
			document.getElementById('PREVIEWPIC').src=decodeURI(document.frmImagePick.BackupImgUrl.value);
		}

	}
	else
	document.getElementById('PREVIEWPIC').src='<?=$GLOBALS['http_path']?>usr/templates/images/imgpreview.gif';
}

function hideall() {
	document.getElementById('DIVSWF').style.display = "none";
	document.getElementById('DIVIMG').style.display = "none";
}

function winonload() {
	<?PHP
	if(file_exists(ROOT_PATH.'usr/templates/'.$_GET["data"]) AND $_GET["data"])
	print 'document.frmImagePick.BackupImgUrl.value = window.opener.document.getElementById(\'src_'.$_GET["qc"].'\').src;';
	else
	print 'document.frmImagePick.BackupImgUrl.value = \''.$GLOBALS['http_path'].'usr/templates/images/imgpreview.gif\';';

	?>
	showPreview();
	clock_status();
}

// -->
</script>


<script language="JavaScript" for="PREVIEWPIC" event="onreadystatechange">
<!--
if(readyState == "complete"){
	PREVIEWPIC.style.visibility = "visible";
	if(document.readyState == "complete"){
		document.frmImagePick.ImgHeight.value = document.PREVIEWPIC.height;
		document.frmImagePick.ImgWidth.value = document.PREVIEWPIC.width;
	}
}
//-->
</script>


<script language="JavaScript">
<!--

function FrameUnload() {
	if(frmImagePick.flag_unload_access.value==0) return false;

	var arr = new Array();

	if (document.frmImagePick.ImgUrl.value.length==0)
	{
		alert('You did not select a picture. Page not updated.');
		arr=null;
	}
	else
	{
		var arg_ImgUrl = document.frmImagePick.BackupImgUrl.value;
		arg_ImgUrl = arg_ImgUrl.split("\\").join("/");
		var arr = arg_ImgUrl.split("\/");
		var arg_ImgUrl = '<?=$_GET["id"]?>.' + arr[arr.length-1];

		obj1 = window.opener.document.getElementById('src_<?=$_GET["qc"]?>');
		obj2 = window.opener.document.getElementById('image_<?=$_GET["qc"]?>');

		//obj1.src = document.frmImagePick.BackupImgUrl.value;
		obj1.src = '<?=$GLOBALS['http_path']?>usr/templates/images/' + arg_ImgUrl;
		obj2.value = 'images/' + arg_ImgUrl;


		<?PHP
		if($_GET["resize"]) {
			if(preg_match("/\*/is", $_GET["resize"]  ))
			list($resize_width, $resize_height) = split("\*", $_GET["resize"]);
			else
			list($resize_width, $resize_height) = split("x", $_GET["resize"]);
			print '
		obj1.width = '.$resize_width.';
		obj1.height = '.$resize_height.';
		';
		} else
		print '
		obj1.width = document.PREVIEWPIC.width;
		obj1.height = document.PREVIEWPIC.height;
		';
		?>
	}

	window.close();
}

var cur_imgname = false;
var cur_imgext = false; // getElementByID()

function ReturnCode() {

	if(cur_imgname==false) return false;
	obj1 = window.opener.document.getElementById('src_<?=$_GET["qc"]?>');
	obj2 = window.opener.document.getElementById('image_<?=$_GET["qc"]?>');
	obj1.src = '<?=$GLOBALS["http_path"]?>usr/templates/images/' + cur_imgname;
	obj2.value = 'images/' + cur_imgname;
	obj1.width = document.PREVIEWPIC.width;
	obj1.height = document.PREVIEWPIC.height;

	window.close();
	return false;
}

function clock_status()  {
	window.setTimeout("clock_status()",100);
	if(document.getElementById('flag_unload_access').value==1) FrameUnload();
	<?PHP
	if( !preg_match("/Gecko/is", $GLOBALS["HTTP_USER_AGENT"]) )
	print '
 	today=new Date();
 	self.status=today.toString();';
	?>
}
// -->
</script>

</HEAD>

<body onload="winonload()">
<form method="post" target="_blank" name="frmImagePick" id="frmImagePick" encType="multipart/form-data" style="padding-top: 0px; padding-bottom: 0px;">
<input type="hidden" name="MAX_FILE_SIZE" value="3000000">
<input type="hidden" name="BackupImgUrl" value="0">
<input type="hidden" name="flag_unload_access" ID="flag_unload_access" value="0">
<input type="hidden" name="qc" value="<?=$_GET["qc"]?>">
<input type="hidden" name="id" value="<?=$_GET["id"]?>">

<div id="mycomputer" align="center">
	<div style="padding-top: 10px; padding-right: 15px; text-align: right; font-size: 14px; height: 28px; background: url(<?=$http_path?>usr/system/images/insimg_bg2.gif) repeat-x;">
	<table width="500" cellpadding="0" cellspacing="0" border="0">
	<tr>
		<td width="328"><img src="<?=$GLOBALS['http_path']?>usr/system/images/x.gif" height="1" weight="266" /></td>
		<td valign="top" align="center" width="130">
		<a style="cursor: pointer;" onclick="mysite.style.display='none'; mycomputer.style.display='block';"><?=$lang["MyComputer"];?></a>
		</td>
		<td valign="top" align="center" width="128">
		<a style="cursor: pointer; color: #4B6576;" onclick="<?PHP if($_GET["iconsize"] or $_GET["resize"]) { print 'alert(\'There is Resize/IconSize Mode\'); return false;'; } ?>mycomputer.style.display='none'; mysite.style.display='block';"><?=$lang["MySite"];?></a>
		</td>
	</tr>
	</table>
	</div>
	<table cellpadding="2" style="margin: 5px 5px 5px 5px" border="0">
	<tr>
		<td valign="top" align="left" nowrap="nowrap">
		<div align="center" style="background-color:gray;overflow:auto;width:450px;height:200px;border-width:1px; border-style:solid;border-color:threeddarkshadow white white threeddarkshadow;">
			<div ID="DIVIMG" style="display: block; border: solid 1px gray">
				<IMG ID="PREVIEWPIC" NAME="PREVIEWPIC" bgcolor="#ffffff" src="<?=$GLOBALS['http_path']?>usr/templates/images/imgpreview.gif" alt="Preview" align="absmiddle" valign="middle" />
			</div>
			<div ID="DIVSWF" style="display: none">
				<object ID="PREVIEWSWF" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0">
				<param name=movie value="<?=$GLOBALS['http_path']?>usr/templates/images/dot.swf">
				<param name="quality" value="high">
				<embed src="<?=$GLOBALS['http_path']?>usr/templates/images/dot.swf" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash">
				</embed>
				</object>
			</div>
		</div>

	</td>
	</tr>
	<tr>
	<td valign="top" align="left" colspan="2" nowrap="nowrap">
	<input type="file" name="ImgUrl" size="40" style="width : 300px;" value="" onChange="showPreview();<?PHP if( preg_match("/Gecko/is", $GLOBALS["HTTP_USER_AGENT"]) ) print ' hideall();'; ?>">
	<?PHP
	if($_GET["resize"]) {

		if(preg_match("/\*/is", $_GET["resize"]  ))
		list($resize_width, $resize_height) = split("\*", $_GET["resize"]);
		else
		list($resize_width, $resize_height) = split("x", $_GET["resize"]);
		print '
		<fieldset style="margin-top: 5px; border: 1px solid #003263;">
				<legend> Resize </legend>
		<div style="padding: 5px;">
		'.$lang["Width"].': '.$resize_width.', &nbsp;
		'.$lang["Height"].': '.$resize_height.'
		<input type="hidden" name="resize_width" value="'.$resize_width.'" />
		<input type="hidden" name="resize_height" value="'.$resize_height.'" />
		</div>
		</fieldset>
		';
	}

	if($_GET["iconsize"]) {

		if(preg_match("/\*/is", $_GET["iconsize"]  ))
		list($icon_width, $icon_height) = split("\*", $_GET["iconsize"]);
		else
		list($icon_width, $icon_height) = split("x", $_GET["iconsize"]);


		print '
		<fieldset style="margin-top: 5px; border: 1px solid #003263;">
				<legend> '.$lang["Icon"].' </legend>
		<div style="padding: 5px;">
		'.$lang["Width"].': '.$icon_width.', &nbsp;
		'.$lang["Height"].': '.$icon_height.'
		<input type="hidden" name="icon_width" value="'.$icon_width.'" />
		<input type="hidden" name="icon_height" value="'.$icon_height.'" />
		</div>
		</fieldset>
		';
	}
	?>


	</td>
	</tr>
	</table>

	<p align="center">
	<button class="sapidcms_cont_btn" id="Ok" onclick="if(document.frmImagePick.ImgUrl.value.length==0) {alert('You did not select a picture. Page not updated.'); return false; } else this.form.submit();">   OK   </button>
	&nbsp;
	<button class="sapidcms_cont_btn" onclick="window.close();"><?=$lang["Cancel"]?></button>
	</p>
	<input type="hidden" size="5" value="0" name="ImgHeight" />
	<input type="hidden" size="5" value="0" name="ImgWidth" />
 </div>


<div id="mysite" style="display: none" align="center">

	<div style="padding-top: 10px; padding-right: 15px; text-align: right; font-size: 14px; height: 28px; background: url(<?=$http_path?>usr/system/images/insimg_bg1.gif) repeat-x;">
	<table width="500" cellpadding="0" cellspacing="0" border="0">
	<tr>
		<td width="328"><img src="<?=$GLOBALS['http_path']?>usr/system/images/x.gif" height="1" weight="266" /></td>
		<td valign="top" align="center" width="130">
		<a style="cursor: pointer; color: #4B6576;" onclick="mysite.style.display='none'; mycomputer.style.display='block';"><?=$lang["MyComputer"];?></a>
		</td>
		<td valign="top" align="center" width="128">
		<a style="cursor: pointer" onclick="mycomputer.style.display='none'; mysite.style.display='block';"><?=$lang["MySite"];?></a>
		</td>
	</tr>
	</table>
	</div>

	<table width="300" cellpadding="2" style="margin: 5px 5px 5px 5px" border="0">
	<tr>
		<td colspan="2" valign="top" align="left" nowrap="nowrap">


	<div align="center" style="background-color:gray;overflow:auto;width:450px;height:200px;border-width:1px; border-style:solid;border-color:threeddarkshadow white white threeddarkshadow;">
		<div ID="DIVIMG1" style="display: block; border: solid 1px gray">
			<IMG ID="PREVIEWPIC1" NAME="PREVIEWPIC1" bgcolor="#ffffff" src="<?=$GLOBALS['http_path']?>usr/templates/images/imgpreview.gif" alt="Preview" align="absmiddle" valign="middle" />
		</div>
		<div ID="DIVSWF1" style="display: none">
			<object ID="PREVIEWSWF1" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0">
			<param name=movie value="<?=$GLOBALS['http_path']?>usr/templates/images/dot.swf">
			<param name="quality" value="high">
			<embed src="<?=$GLOBALS['http_path']?>usr/templates/images/dot.swf" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash">
			</embed>
			</object>
		</div>
	</div>
		</td>
	</tr>


	<tr>
		<td valign="top" align="left" nowrap="nowrap">
		</td>
		<td valign="top" align="left" nowrap="nowrap">
		<input ID="insertbtn" name="insertbtn1" style="display: none" class="sapidcms_cont_btn" type="button" value="<?=$lang["Insert_Picture"]?>" onclick="ReturnCode()" />
		</td>
	</tr>


	<tr>
		<td colspan="2" valign="top" align="left" nowrap="nowrap">

	<div align="left" style="background-color: white; overflow:auto;width:450px;height:200px;border-width:1px; border-style:solid;border-color:threeddarkshadow white white threeddarkshadow; padding: 5px;">
		<table  cellpadding="1" border="0">
		<?PHP
		$d = dir(ROOT_PATH."usr/templates/images/");
		while (false !== ($entry = $d->read())) {
			if($entry!="." AND $entry!=".." AND is_file(ROOT_PATH."usr/templates/images/".$entry)) {
				echo "<tr><td style=\"border-bottom: 1px dotted black\"><a style=\"cursor: pointer;\"
		   	".( preg_match("/\.swf$/is", $entry) ?
		   	"onclick=\"
		   		insertbtn.style.display	 = 'block'; DIVIMG1.style.display = 'none'; DIVSWF1.style.display = 'block'; cur_imgname='$entry'; cur_imgext='swf';
				document.PREVIEWSWF1.Movie=decodeURI('".$http_path."usr/templates/images/".$entry."');
		   	\"" :
		   	"onclick=\"
		   		insertbtn.style.display = 'block'; DIVIMG1.style.display = 'block'; DIVSWF1.style.display = 'none'; cur_imgname='$entry'; cur_imgext='img';
		   	PREVIEWPIC1.src='".$http_path."usr/templates/images/".$entry."';\"" )."
		   	>".$entry."</a></td>\n";
		   	echo "<td style=\"padding-left: 10px; border-bottom: 1px dotted black\">".filesize(ROOT_PATH."usr/templates/images/".$entry)." bytes</td></tr>";
			}
		}
		$d->close();
		?>
		</table>
	</div>


		</td>
	</tr>
	</table>
	</form>
</div>

</body>
</html>